package com.vaye.common.utils;

import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  全局用户信息工具类
 * @author wangzhiyong
 * @date 2022/6/14 下午1:50
 * @return null
 */
public class UserContextHolder {
    private static ThreadLocal<String> userInfoHolder = new ThreadLocal();

    public static void setUserName(String userName){
        if(ObjectUtils.isEmpty(userInfoHolder.get())){
            userInfoHolder.set(userName);
        }
    }

    /**
     *  获取用户名
     * @author wangzhiyong
     * @date 2022/6/14 下午1:47
     * @return java.lang.String
     */
    public static String getUserName(){
        return userInfoHolder.get();
    }

    /**
     * 获取请求IP
     * @author wangzhiyong
     * @date 2022/11/8 上午9:14
     * @return java.lang.String
     */
    public static String getIp() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static void clearCurrentUser(){
        userInfoHolder.remove();
    }
}
